package tmproject.hlhj.fhp.cartrans.customVIews

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.os.Bundle
import android.view.View
import com.tbruyelle.rxpermissions.RxPermissions
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.MimeType
import com.zhihu.matisse.engine.impl.GlideEngine
import com.zhihu.matisse.internal.entity.CaptureStrategy
import kotlinx.android.synthetic.main.dialog_confirm.*
import rx.functions.Action1
import tmproject.hlhj.fhp.cartrans.BaseAty
import tmproject.hlhj.fhp.cartrans.R
import android.content.pm.ActivityInfo
import android.os.Handler
import android.os.Message
import android.support.v7.app.AppCompatActivity
import android.view.Gravity
import com.bumptech.glide.Glide
import com.huantansheng.easyphotos.EasyPhotos
import com.lzy.okgo.model.Response
import com.zhihu.matisse.filter.Filter.K
import kotlinx.android.synthetic.main.aty_home.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import tmproject.hlhj.fhp.cartrans.MainActivity
import tmproject.hlhj.fhp.cartrans.activitys.CameraAty
import tmproject.hlhj.fhp.cartrans.activitys.HomeAty
import tmproject.hlhj.fhp.cartrans.event.PathEvent
import tmproject.hlhj.fhp.cartrans.http.Apis
import tmproject.hlhj.fhp.cartrans.http.BaseObserver
import tmproject.hlhj.fhp.cartrans.http.LoadingAction
import tmproject.hlhj.fhp.cartrans.javaBean.BaseBean
import tmproject.hlhj.fhp.cartrans.javaBean.SaveClassBean
import tmproject.hlhj.fhp.cartrans.log
import tmproject.hlhj.fhp.cartrans.utils.FileUtils
import tmproject.hlhj.fhp.cartrans.utils.SpHelper
import tmproject.hlhj.fhp.cartrans.utils.ToastUtils
import java.io.File


/**
 * Created by Never Fear   on 2018\8\28 0028.
Never More....
 type 1 考试认证 。 2- 学习认证
 */

class ConfirmDialog(private val c:Context,private val type:Int,private val bundle: Bundle?) :Dialog(c, R.style.MyDialog), SignDialog.OnSignOverListener {
    private val TAKE_PHOTO=111
    var listener:OnCommitListener?=null
    override fun over(bit: Bitmap) {
        log("fhp","???????????????????????????")
        tv2.visibility=View.GONE
        signImg.setImageBitmap(bit)
        signFile = FileUtils.createImageFile(bit, c)
    }
    private lateinit var signPop:SignPop
    private var photoPath:String?=null
    private var signFile:File?=null
    private lateinit var signDialog:SignDialog
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.dialog_confirm)
        log("fhp","来一次？")

        EventBus.getDefault().register(this)
        signDialog=SignDialog(c,this)
        signPop= SignPop(c,this)
        btClose.setOnClickListener {
            dismiss()
        }
        btSign.setOnClickListener {
            val aty = c as AppCompatActivity
            aty.requestedOrientation=ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
            signDialog.show()
        }

        btTakePhoto.setOnClickListener {
            if (!RxPermissions.getInstance(c).isGranted(Manifest.permission.CAMERA)||!RxPermissions.getInstance(c).isGranted(Manifest.permission.RECORD_AUDIO)){
                RxPermissions.getInstance(c).request(Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.CAMERA)
                        .subscribe(object :Action1<Boolean>{
                            override fun call(t: Boolean?) {
                                if (t!!){
                                    val intent = Intent(c, CameraAty::class.java)
                                    c.startActivity(intent)
                                   /* EasyPhotos.createAlbum(c as Activity, true,MyGlideEngin())//参数说明：上下文，是否显示相机按钮，[配置Glide为图片加载引擎](https://github.com/HuanTanSheng/EasyPhotos/wiki/12-%E9%85%8D%E7%BD%AEImageEngine%EF%BC%8C%E6%94%AF%E6%8C%81%E6%89%80%E6%9C%89%E5%9B%BE%E7%89%87%E5%8A%A0%E8%BD%BD%E5%BA%93)
                                            .setFileProviderAuthority("tmproject.hlhj.fhp.fileprovider")//参数说明：见下方`FileProvider的配置`
                                            .start(TAKE_PHOTO);*/
                                }else{
                                    dismiss()
                                }
                            }
                        })
            }else{
                /*EasyPhotos.createAlbum(c as Activity, true,MyGlideEngin())//参数说明：上下文，是否显示相机按钮，[配置Glide为图片加载引擎](https://github.com/HuanTanSheng/EasyPhotos/wiki/12-%E9%85%8D%E7%BD%AEImageEngine%EF%BC%8C%E6%94%AF%E6%8C%81%E6%89%80%E6%9C%89%E5%9B%BE%E7%89%87%E5%8A%A0%E8%BD%BD%E5%BA%93)
                        .setFileProviderAuthority("tmproject.hlhj.fhp.fileprovider")//参数说明：见下方`FileProvider的配置`
                        .start(TAKE_PHOTO);*/
                val intent = Intent(c, CameraAty::class.java)
                c.startActivity(intent)
            }

        }
        btCommit.setOnClickListener {
            if (photoPath==null||signFile==null){
                ToastUtils.toast("请填写完整")
                return@setOnClickListener
            }
            if (type==1){
                Apis.commitExam(SpHelper.getToken(c),
                        bundle!!.getInt("id"),bundle.getInt("cNum"),File(photoPath),signFile!!)
                        ?.let {
                            it.doOnSubscribe(LoadingAction(c))
                                    .subscribe(object :BaseObserver<Response<BaseBean>>(c){
                                        override fun failed(e: Throwable?) {
                                        }
                                        override fun httpSuccess(t: Response<BaseBean>) {
                                            ToastUtils.toast("提交试卷成功")
                                            listener?.over()
                                            dismiss()
                                        }
                                        override fun httpErroCode(baseBean: BaseBean) {
                                        }
                                    })
                        }
            }else{
                Apis
                        .saveClass(SpHelper.getToken(c),bundle?.getInt("id")!!
                                ,bundle.getString("learned_time"),File(photoPath),signFile!!)
                        ?.let {
                            it.doOnSubscribe(LoadingAction(c))
                                    .subscribe(object :BaseObserver<Response<SaveClassBean>>(c){
                                        override fun failed(e: Throwable?) {
                                        }

                                        override fun httpSuccess(t: Response<SaveClassBean>) {
                                            ToastUtils.toast("提交成功")
                                            listener?.over()
                                            dismiss()
                                        }

                                        override fun httpErroCode(baseBean: BaseBean) {
                                        }
                                    })
                        }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public fun setImg(pathEvent: PathEvent){

        img.visibility=View.VISIBLE
        photoPath=pathEvent.path
        Glide.with(c).load(pathEvent.path).into(img)
        loImg.visibility=View.GONE
    }

    override fun dismiss() {
        EventBus.getDefault().unregister(this)
        super.dismiss()
    }
    interface OnCommitListener{
        fun over()
    }
}